import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.io.*;

/**
 * An object of class ContactsList adds new contact object to a ContactsList
 * object and prints the sorted contacts in the list.
 * retrieves any contact(s) having same last name
 * 
 * @author Soyoung
 * 
 */
public class ContactsList implements Serializable {
	private List<Contact> contactList; // Data member

	public ContactsList() { // Constructor
		contactList = new ArrayList<Contact>();
	}

	/**
	 * Returns string of classes in contactList
	 * @return String
	 */
	public String toString (){
		String contactString;
		contactString = "";
		for (Contact cContact : contactList)
			contactString += cContact;
		return contactString;
	}

	/**
	 * Retrieve contact(s) having same last name and
	 * sets the result to contactList to print
	 * 
	 * @param String lastName
	 * @author Soyoung, Josh Zeiser
	 */

	public ContactsList retrieveContact(String lastName) {
		ContactsList listHolder; 	// To hold the result retrieved
		listHolder = new ContactsList();
		Name compareName;
		compareName = new Name();
		compareName.setlName(lastName);
		Contact compareContact;
		compareContact = new Contact();
		compareContact.setName(compareName);
		for (Contact cContact : contactList) {
			if (cContact.compareTo(compareContact) == 0)
				listHolder.addContact(cContact);
		}
		return listHolder;
	}
	
	/**
	 * Sort the list by last name
	 */
	public void sortList() {
		Collections.sort(contactList);
	}

	/**
	 * Adds a Contact as a data member of a ContactsList ArrayList
	 * then sort the list
	 * @param Contact
	 * @author MS, Soyoung
	 */
	public void addContact(Contact contact) {
		if (contact.getName().getlName().equals("")) {
			System.out
					.println("The contact was not added because no last name was entered.");
		} else {
			contactList.add(contact);
			this.sortList(); //Sort the list 
		}
	}

	/**
	 * Calculates length of the instance of object ContactsList
	 * @return int
	 */
	public int size() {
		int counter;
		List<Contact> listHolder;
		listHolder = new ArrayList<Contact>();
		listHolder = contactList;
		counter = listHolder.size();
		return counter;
	}
}